// pages/growthRecord/growthRecord.js
import * as utils from '../../utils/util.js'
import request from '../../utils/http.js'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    year: new Date().getFullYear(),
    weight:'',//宝宝体重
    stature:'',//宝宝身高
    headCircumference:'',//宝宝头围
    time: "请选择日期",//添加事件
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    maxDate: new Date(2119, 1, 1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      } else {
        return `${value}日`;
      }
    },
    show: false,
    babyId:'',
    babyGrowthRecord:[],//宝宝成长记录数据
    babyMVlist:[],//宝宝成长影像记录
    active:0,
    babyList:[],
    changeBabyData:{},
    ageStr:'',
    currentIndex:0,
    staturerule:'',//身高验证
    weightrule:'',//体重验证
    headCircumferencerule:''//头围验证
  },
  rules(e){
    console.log(e)
    let type = 1
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function(options){
    let that = this;
    console.log(options)
    if(options.babyId != ''){
      that.setData({
        babyId: options.babyId,
        active: Number(options.active)
      })
    }else{
      that.setData({
        active: Number(options.active)
      })
    }
  },
  /**
 * 生命周期函数--监听页面显示
 */
  onShow:function() {
    let that = this;
    //获取宝宝列表
    that.getBabyList();
    // 调用函数时，返回值是日期和时间
    var time = utils.getNowFormatDate();
    // 再通过setData更改Page()里面的data，动态更新页面的数据
    this.setData({
      time: time
    });
  },
  //获取宝宝列表
  getBabyList(){

    let that = this;
    let babyId = that.data.babyId;
    request({
      url: "/baby-cloud-base/mobileBabyInfo/listAll",
      method: "post"
    }).then(res => {
      if (res.data.code == 200 && res.data.data.length > 0) {
        let list = res.data.data;
        let currentIndex = 0;
        if (babyId != ''){
          list.forEach((item, index) => {
            if (item.id === babyId) {
              currentIndex = index
            }
          })
        }
        this.setData({
          currentIndex: currentIndex,
          babyList: list,
          changeBabyData: list[currentIndex],
          babyId: list[currentIndex].id,
          ageStr: utils.getBirthSlot(list[currentIndex].birthday.split(" ")[0])
        })
        //获取宝宝成长记录 （成长影像/成长记录）
        that.getBabyRecord(list[currentIndex].id)
        //获取宝宝成长影像
        that.getBabyRecordMV(list[currentIndex].id)
      }
    });
  },
  //选择宝宝头像时 需要展示的数据
  changeBabyHeader(e) {
    let that = this;
    this.setData({
      currentIndex: e.target.dataset.idx,
      changeBabyData: that.data.babyList[e.target.dataset.idx],
      babyId: that.data.babyList[e.target.dataset.idx].id,
      ageStr: utils.getBirthSlot(that.data.babyList[e.target.dataset.idx].birthday.split(" ")[0])
    })
    that.getBabyRecord(that.data.babyList[e.target.dataset.idx].id) //获取宝宝成长记录
    that.getBabyRecordMV(that.data.babyList[e.target.dataset.idx].id)//获取宝宝成长影像
  },
  deleteMV(e){
    let that = this;
    let id = e.target.dataset.id;
    wx.showModal({
      title: '提示',
      content: '是否删除该回忆？',
      success(res) {
        if (res.confirm) {
          request({
            url:'/baby-cloud-base/mobileGrowthVideo/delete',
            method:'post',
            data:{
              id
            }
          }).then(res=>{
            if(res.data.code == 200){
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                duration: 1000
              })
              that.getBabyRecordMV(that.data.babyId)//获取宝宝成长影像
            }
          })
        } else if (res.cancel) {
          return 
        }
      }
    })
  },
  //获取宝宝成长记录
  getBabyRecord(babyId){
    request({
      url:"/baby-cloud-base/mobileGrowthRecord/list",
      method:"post",
      data:{
        babyId
      }
    }).then(res=>{
      if(res.data.code == 200){
        res.data.data.forEach((item)=>{
          item.recordTime = item.recordTime.split(' ')[0]
          item.ageStr = utils.getBirthOfDay(item.between+1)
        })
        this.setData({
          babyGrowthRecord:res.data.data
        })
      }
    })
  },
  //获取宝宝成长影像
  getBabyRecordMV(babyId){
    request({
      url:'/baby-cloud-base/mobileGrowthVideo/list',
      method: "post",
      data: {
        babyId
      }
    }).then(res=>{
      if(res.data.code == 200){
        console.log(res.data.data)
        res.data.data.forEach(item=>{
          if (item.growthType == 0){
            item.picJson = item.picJson.split(',')
          }
          item["time"] = item.addTime.split(" ")[1]
          item.addTime = item.addTime.split(" ")[0]
        })
        this.setData({
          babyMVlist:res.data.data
        })
      }
    })
  },

  headCircumferencechange(e){
    //宝宝头围输入触发事件
    this.setData({
      headCircumference: e.detail
    })
  },
  weightchange(e){
    //体重输入触发事件
    this.setData({
      weight: e.detail
    })
  },
  staturechange(e){
    let type = e.currentTarget.dataset.type;
    let num = Number(e.detail)
    let isFloat = e.detail.indexOf(".")+1;
    if(type == 'sg'){
      if(num < 40 || num > 190){
        this.setData({
          staturerule: `范围40cm(包含)-190cm(包含)`,
        })
      } else if (isFloat>0){ //是浮点型 小数
        console.log(isFloat)
        let count = e.detail.length - isFloat;
        if (count > 1){
          this.setData({
            staturerule: `小数点后最多输入一位小数`,
          })
        } else if (count == 1){
          this.setData({
            staturerule: ``,
            stature: num
          })
        }
      }else{
        this.setData({
          staturerule: ``,
          stature:num
        })
      }
    } else if (type == 'tz'){
      if (num < 1.5 || num > 75) {
        this.setData({
          weightrule: `范围1.5kg(包含)-75 kg(包含)`
        })
      } else if (isFloat > 0) { //是浮点型 小数
        let count = e.detail.length - isFloat;
        if (count > 1) {
          this.setData({
            weightrule: `小数点后最多输入一位小数`
          })
        } else if (count == 1){
          this.setData({
            weightrule: ``,
            weight: num
          })
        }
      }else{
        this.setData({
          weightrule: ``,
          weight:num
        })
      }
    }else if(type == 'tw'){
      if (num < 30 || num > 70) {
        this.setData({
          headCircumferencerule: `范围30cm(包含)-70 cm(包含)`
        })
      } else if (isFloat > 0) { //是浮点型 小数
        let count = e.detail.length - isFloat;
        if (count > 1) {
          this.setData({
            headCircumferencerule: `小数点后最多输入一位小数`
          })
        } else if (count == 1){
          this.setData({
            headCircumferencerule: ``,
            headCircumference: num
          })
        }
      } else {
        this.setData({
          headCircumferencerule: ``,
          headCircumference:num
        })
      }
    }
  },
  addBabyrecordCover(){
    let that = this;
    let obj = {};
    Object.assign(obj, {
      babyId:that.data.babyId || '',
      height: that.data.stature || '',
      weight: that.data.weight || '',
      recordTime: that.data.time || '',
      headCircumference: that.data.headCircumference || '',
    })
    console.log(that.data.babyId)
    console.log(obj)
    let flag = utils.rules(obj);
    console.log(flag.name)
    switch (flag.name) {
      // case 'headCircumference':
      //   wx.showToast({
      //     title: '请输入宝宝头围',
      //     icon: 'none',
      //     duration: 2000
      //   })
      //   return;
      //   break;
      case 'height':
        wx.showToast({
          title: '请输入宝宝身高',
          icon: 'none',
          duration: 2000
        })
        return;
        break;
      case 'weight':
        wx.showToast({
          title: '请输入宝宝体重',
          icon: 'none',
          duration: 2000
        })
        return;
        break;
      default:
        if ( that.data.weightrule != '' || that.data.staturerule != ''){
          return
        }
        wx.showLoading()
        // 发送数据给服务器
        request({
          url: "/baby-cloud-base/mobileGrowthRecord/addItem",
          method: "POST",
          data:{
            ...obj
          }
        }).then(res => {
          console.log(res)
          if (res.data.code == 200) {
            //添加宝宝成功跳转至首页
            wx.hideLoading()
            wx.showToast({
              title: '添加成功',
              icon: 'none',
              duration: 2000
            })
            that.getBabyRecord(that.data.changeBabyData.id);
            that.setData({
              show:false
            })
          }else{
            wx.hideLoading()
          }
        }, err => {
          console.log(err)
        })
        break;
    }

  },
  popup(){
    this.setData({
      show: true,
      stature:'',
      weight:'',
      headCircumference:''
    })
  },
  onClose() {
    if (this.data.stature != '' && this.data.weight != '' && this.data.headCircumference != '' ){
      let that=this
      wx.showModal({
        title: '系统提示',
        content: '您本次修改还未保存，是否保存？',
        success(res) {
          if (res.confirm) {
            that.addBabyrecordCover()
          } else if (res.cancel) {
            that.setData({
              show: false,
              stature: '',
              weight: '',
              headCircumference: ''
            })
          }
        }
      })
    }else{
      this.setData({
        show: false,
        stature: '',
        weight: '',
        headCircumference: ''
      })
    }
    
  },
  //上传图片或视频
  openUpload () {
    let that = this;
    wx.showActionSheet({
      itemList: ['照片', '视频'],
      success(res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0){
          //照片
          wx.navigateTo({
            url: '/pages/publicationRecord/publicationRecord?type=' + res.tapIndex + '&babyId=' + that.data.babyId,
          })
        } else if (res.tapIndex == 1){
          //视频
          wx.navigateTo({
            url: '/pages/publicationRecord/publicationRecord?type=' + res.tapIndex + '&babyId=' + that.data.babyId,
          })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  preViewImgs(e){
    //点击图片预览
    console.log(e)
    let index = e.target.dataset.curentindex;
    let src = e.target.dataset.src;
    let imgs = this.data.babyMVlist[index].picJson;
    wx.previewImage({
      current: src, // 当前显示图片的http链接  
      urls: imgs // 需要预览的图片http链接列表  
    })
  }
})